package com.judian.smart.base;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.iflytek.cloud.SpeechUtility;
import com.judian.jdmusicsdk.presenter.JdPlayPresenter;
import com.tencent.bugly.crashreport.CrashReport;
import com.judian.smart.R;
import com.judian.smart.activity.MainActivity;
import com.judian.smart.constant.Constants;
import com.judian.smart.factory.DeviceFactory;
import com.judian.smart.factory.GateWayFactory;
import com.judian.smart.factory.ModeFactory;
import com.judian.smart.factory.ModeListFactory;
import com.judian.smart.factory.RoomFactory;
import com.judian.smart.net.TcpSender;
import com.judian.smart.netty.NettySocketClient;
import com.judian.smart.service.GateWayService;
import com.judian.smart.util.AudioManagerUtil;
import com.judian.smart.util.CrashCollector;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * author: Peter
 * date: 2019/08/05 星期一 18:35
 * desc: Activity基类
 * //  ┏┓　　    ┏┓
 * //┏━┛┻━━━━━━━┛┻┓
 * //┃　　　　　　 ┃
 * //┃　　　━　　  ┃
 * //┃　━┳┛　 ┗┳━ ┃
 * //┃　　　　　   ┃
 * //┃　　　┻　　　┃
 * //┃　　　　　　 ┃
 * //┗━━┓　　　┏━━┛
 * //   ┃　　　┃   神兽保佑
 * //   ┃　　　┃   代码无BUG！
 * //   ┃　　　┗━━━┓
 * //   ┃　　　　　 ┣┓
 * //   ┃　　　　　 ┏┛
 * //   ┗━┓┓┏━━┳┓┏┛
 * //     ┃┫┫　┃┫┫
 * //     ┗┻┛　┗┻┛
 */
public class MyApplication extends MultiDexApplication {
    public static final String TAG = MyApplication.class.getSimpleName();
    private static MyApplication instance = null;
    private Intent gatewayService;
    private GateWayService.CameraBinder cameraBinder;
    private String WifiName;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "生命周期 onCreate: !!!!!!!!!!!!!!!!!!");
        initData();  //初始化数据
        initFiles();  //初始化数据库文件
    }



    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //解决 android Didn't find class "xxx.xxx.MyApplication" on path: DexPathList 错误
        MultiDex.install(base);
    }

    //初始化数据
    private void initData() {
        instance = this;    //初始化MyApplication实例
        JdPlayPresenter.getInstance().init(this);   //声必可初始化
        SpeechUtility.createUtility(this, "appid=" + getString(R.string.app_id));  //初始化讯飞语音
        CrashReport.initCrashReport(getApplicationContext(), "62b7bea8ec", true); //bugly
        CrashCollector.getInstance().init(this); //初始化崩溃日志收集器
        AudioManagerUtil.get().registerReceiver();  //注册AudioManagerUtil广播
    }


    //初始化数据库文件
    public void initFiles() {
        isExists();
        String file = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "ZunderHome" + File.separator + "/Root/homedatabases.db";
        if (!new File(file).exists()) {
            FileOutputStream fos;
            InputStream is;
            try {
                is = getResources().openRawResource(R.raw.homedatabases);
                fos = new FileOutputStream(file);
                byte[] buffer = new byte[8192];
                int count;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                    fos.flush();
                }
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }

    public void isExists() {
        String path = getRootPath();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        path = getRootPath() + "/Root";
        file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        path = getRootPath() + "/SImage";
        file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
    }

    public static MyApplication getInstance() {
        if (instance == null) {
            instance = new MyApplication();
        }
        return instance;
    }

    public String getRootPath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ZunderHome";
    }

    public void sendBroadCast(String resultStr) {
        Intent intent = new Intent("com.zunder.smart.receiver");
        Bundle bundle = new Bundle();
        bundle.putString("str", resultStr);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }


    public String getAPPVersion() {
        String result;
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            result = info.versionName;

        } catch (Exception e) {
            result = "0.0.0";
        }
        return result;
    }

    /**
     * 刷新专案
     */
    public void updateFresh() {
        TcpSender.isGateWay = false;
        stopGateWayServer();
        startGateWayServer();

        GateWayFactory.clearList();
        RoomFactory.clearList();
        DeviceFactory.clearList();
        ModeFactory.getInstance().clearList();
        ModeListFactory.getInstance().clearList();
        if (Constants.isCheckProject == 0) {
            MainActivity.mInstance.updateListView();
        }
        if (!NettySocketClient.getInstans().isConnect()) {
            try {
                MainActivity.mInstance.initSocket();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String getMusicDirectory(String musicName) {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ZunderHome" + File.separator + "music";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        String filePath = path + File.separator + musicName;
        if (new File(filePath).exists()) {
            path += File.separator + musicName;
        } else {
            path = "";
        }
        return path;
    }

    /**
     * 开启连接网关服务
     */
    public void startGateWayServer() {
        gatewayService = new Intent(this, GateWayService.class);
        bindService(gatewayService, conn, Service.BIND_AUTO_CREATE);
    }

    /**
     * 停止连接网关服务
     */
    public void stopGateWayServer() {
        if (gatewayService != null) {
            unbindService(conn);
            cameraBinder.stopFindDevice();
            gatewayService = null;
        }
    }

    public String getWifiName() {
        return WifiName;
    }

    public void setWifiName(String wifiName) {
        WifiName = wifiName;
    }

    /**
     * ServiceConnection连接对象
     */
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            cameraBinder = (GateWayService.CameraBinder) iBinder;
            cameraBinder.startFindDevice();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            cameraBinder.stopFindDevice();
        }
    };
}
